import { FeatureTable, BatchTable } from '../../assets/loader/3dtiles/FeatureTable';
import { loadGLTFObject } from '../../assets/loader/gltf/gltfParse';
import { Matrix4 } from '../../core/math/Matrix4';
/**
 * @class
 * @memberof w.parser
 * @param {*} message 消息
 * @param {*} callback 处理完成的回调
 */
async function b3dm(message, callback) {
  const path = message.path
  const matrix = new Matrix4()
  fetch(message.path).then(result => {
    if (!result.ok) {
      console.error("不能加载瓦片 : " + path)
      throw new Error(`不能加载 "${path}". 加载状态 ${result.status} : ${result.statusText}`);
    }
    return result.arrayBuffer();

  }).then(async arrayBuffer => {
    const dataView = new DataView(arrayBuffer);
    const magic =
      String.fromCharCode(dataView.getUint8(0)) +
      String.fromCharCode(dataView.getUint8(1)) +
      String.fromCharCode(dataView.getUint8(2)) +
      String.fromCharCode(dataView.getUint8(3));
    console.assert(magic === 'b3dm');
    const byteLength = dataView.getUint32(8, true);
    console.assert(byteLength === arrayBuffer.byteLength);

    const featureTableJSONByteLength = dataView.getUint32(12, true);
    const featureTableBinaryByteLength = dataView.getUint32(16, true);
    const batchTableJSONByteLength = dataView.getUint32(20, true);
    const batchTableBinaryByteLength = dataView.getUint32(24, true);
    const featureTableStart = 28;
    const featureTable = new FeatureTable(arrayBuffer, featureTableStart, featureTableJSONByteLength, featureTableBinaryByteLength);

    const batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
    const batchTable = new BatchTable(arrayBuffer, featureTable.getData('BATCH_LENGTH'), batchTableStart, batchTableJSONByteLength, batchTableBinaryByteLength);

    const glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
    const glbBytes = new Uint8Array(arrayBuffer, glbStart, byteLength - glbStart);


    const gltfBuffer = glbBytes.slice().buffer;
    const jsonLength = new Uint32Array(gltfBuffer, 12, 1)[0];
    const jsonChunk = new Uint8Array(gltfBuffer, 20, jsonLength);
    const json = JSON.parse(new TextDecoder("utf-8").decode(jsonChunk));
    let options = { optimize: true, matrix, json, url: path, glb: gltfBuffer, glbOffset: 28 + jsonLength }
    let gltfObject = await loadGLTFObject(options);
    let transferlist = gltfObject.transferlist
    transferlist.push(...gltfObject.images)
    delete gltfObject.transferlist
    delete gltfObject.buffers
    delete gltfObject.json
    delete gltfObject.meshes
    delete gltfObject.nodes
    delete gltfObject.scenes
    delete gltfObject.worldMatrix
    callback({ data: gltfObject, transferlist: transferlist });

  })


}
export { b3dm }